<template>
  <el-row style="margin-bottom: 100px">
    <el-col :span="24">
      <el-tabs v-model="activeName">
        <el-tab-pane label="回复管理" name="first">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>回复列表</span>
              <p class="tip">如果需要修改某回复请点击查看按钮</p>
            </div>
            <div style="padding:0 15px">
              <el-table
                :data="newsDataList"
                style="width: 100%">
                <el-table-column
                  prop="title"
                  label="回复名称">
                </el-table-column>
                <el-table-column
                  prop="menuKey"
                  label="菜单回复规则">
                </el-table-column>
                <el-table-column
                  prop="textKey"
                  label="自动回复规则">
                </el-table-column>
                <el-table-column
                  prop="weight"
                  label="权重">
                </el-table-column>
                <el-table-column
                  label="操作">
                  <template slot-scope="scope">
                    <el-button @click="viewText(scope.row)" type="text" size="small">查看</el-button>
                    <el-button @click="deleteText(scope.row._id)" type="text" size="small">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="添加回复" name="second" style="margin-bottom: 20px">
          <el-row style="padding-right:15px ">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>回复规则</span>
              </div>
              <div class="">
                <el-input placeholder="该回复名称" v-model="newsData.title">
                  <template slot="prepend">该回复名称</template>
                </el-input>
                <p class="tip">
                  用于区分回复（不能为空）
                </p>
              </div>
              <div style="margin-top: 20px">
                <el-input placeholder="菜单匹配规则" v-model="newsData.menuKey">
                  <template slot="prepend">菜单匹配规则</template>
                </el-input>
                <p class="tip">
                  菜单匹配规则是与自定义菜单中的匹配规则相对应！（可为空,建议使用英文字母,不能和其他回复有重复）
                </p>
              </div>
              <div style="margin-top: 20px">
                <el-input placeholder="自动回复规则" v-model="newsData.textKey">
                  <template slot="prepend">自动回复规则</template>
                </el-input>
                <p class="tip">
                  自动回复规则是当用户给公众号发送相关文字消息，公众号会根据相关设置自动回复!（注意！！此回复规则和图文回复规则不能重复，重复则判断权重，权重相同的随机回复其中一个）
                </p>
              </div>
              <div style="margin-top: 20px">
                <el-input placeholder="自动回复权重" v-model="newsData.weight">
                  <template slot="prepend">回复权重</template>
                </el-input>
                <p class="tip">
                  如自动回复规则有重复，则回复权重大者！只能为数字（如：订阅公众号 权重为1 ，服务公众号 权重为2。 用户发送 ‘公’，‘公众’，‘公众号’等字时，给用户的展示内容为‘服务公众号’）
                </p>
              </div>
            </el-card>
          </el-row>
          <el-row>
            <el-col :span="7">
              <div class="news-view">
                <div class="news-page">
                  <el-card class="box-card">
                    <div slot="header" class="clearfix">
                      <span>图文展示</span>
                    </div>
                    <div v-if="!contentHide" class="news-container">
                      <ul class="news-content">
                        <li v-if="articles.length == 1">
                          <div class="mainImg">
                            <img :src="'http://localhost:3000/weChat/wximg?url='+articles[0].thumb_url">
                            <div class="singleTitle">
                              {{articles[0].title}}
                              <div class="digest">
                                {{articles[0].digest}}
                              </div>
                            </div>
                          </div>
                        </li>
                        <li v-else="articles.length > 1">
                          <div class="mainImg">
                            <img :src="'http://localhost:3000/weChat/wximg?url='+articles[0].thumb_url">
                            <div class="mainTitle">
                              {{articles[0].title}}
                            </div>
                          </div>
                          <div class="operation" style="     line-height: 250px;">
                            <a href="javascript:" @click="editNews(0)">编辑</a>
                            <a href="javascript:" @click="delNews(0)" style="margin-left: 20px">删除</a>
                          </div>
                        </li>
                        <li v-for="(item, index) in articles" v-if="index >= 1 && articles.length > 1"
                            class="clearfix">
                          <div class="viceTitle">
                            <div>
                              {{articles[index].title}}
                            </div>
                          </div>
                          <div class="viceImg">
                            <img :src="'http://localhost:3000/weChat/wximg?url='+articles[index].thumb_url">
                          </div>
                          <div class="operation" style="line-height: 140px;">
                            <a href="javascript:" @click="editNews(index)">编辑</a>
                            <a href="javascript:" @click="delNews(index)" style="margin-left: 20px">删除</a>
                          </div>
                        </li>
                        <li v-if="articles.length < 8">
                          <div class="addNews" @click="addNews()" title="添加图文">
                            +
                          </div>
                        </li>
                      </ul>
                    </div>
                    <div class="news-container" v-else>
                      <ul class="news-content">
                        <li v-if="externalNews.length == 1">
                          <div class="mainImg">
                            <img :src="externalNews[0].picurl">
                            <div class="singleTitle">
                              {{externalNews[0].title}}
                              <div class="digest">
                                {{externalNews[0].description}}
                              </div>
                            </div>
                          </div>
                        </li>
                        <li v-else="externalNews.length > 1">
                          <div class="mainImg">
                            <img :src="externalNews[0].picurl">
                            <div class="mainTitle">
                              {{externalNews[0].title}}
                            </div>
                          </div>
                          <div class="operation" style="     line-height: 250px;">
                            <a href="javascript:" @click="editNews(0,'external')">编辑</a>
                            <a href="javascript:" @click="delNews(0,'external')" style="margin-left: 20px">删除</a>
                          </div>
                        </li>
                        <li v-for="(item, index) in externalNews" v-if="index >= 1 && externalNews.length > 1"
                            class="clearfix">
                          <div class="viceTitle">
                            <div>
                              {{externalNews[index].title}}
                            </div>
                          </div>
                          <div class="viceImg">
                            <img :src="externalNews[index].picurl">
                          </div>
                          <div class="operation" style="line-height: 140px;">
                            <a href="javascript:" @click="editNews(index,'external')">编辑</a>
                            <a href="javascript:" @click="delNews(index,'external')" style="margin-left: 20px">删除</a>
                          </div>
                        </li>
                        <li v-if="externalNews.length < 8">
                          <div class="addNews" @click="addNews('external')" title="添加图文">
                            +
                          </div>
                        </li>
                      </ul>
                    </div>
                  </el-card>
                </div>
              </div>
            </el-col>
            <el-col :span="17">
              <div style="padding-right:15px " class="news-set">
                <el-card class="box-card">
                  <div slot="header">
                    <span>图文设置</span>
                    <el-switch
                      v-model="contentHide"
                      active-color="#409eff"
                      inactive-color="#ff4949"
                      active-text="外部跳转">
                    </el-switch>
                  </div>
                  <div v-if="!contentHide">
                    <div>
                      <el-input placeholder="标题" v-model="articles[articlesIndex].title">
                        <template slot="prepend">标题</template>
                      </el-input>
                      <p class="tip">
                        标题不能超过64字符，1中文=2字符，1英文=1字符
                      </p>
                    </div>
                    <div style="margin-top: 15px">
                      <el-input placeholder="作者" v-model="articles[articlesIndex].authod">
                        <template slot="prepend">作者</template>
                      </el-input>
                    </div>
                    <div style="margin-top: 15px" v-if="articles.length == 1">
                      <el-input placeholder="摘要" v-model="articles[articlesIndex].digest">
                        <template slot="prepend">摘要</template>
                      </el-input>
                      <p class="tip">
                        图文消息的摘要，仅有单图文消息才有摘要，多图文此处为空
                      </p>
                    </div>
                    <div style="margin-top: 15px">
                      <div class="clearfix">
                        <span class="title">图片上传</span>
                        <div class="content">
                          <el-upload
                            class="upload-demo"
                            action="/weChat/uploadPerpetualMaterial?type=image"
                            :on-success="uploadSuccessWX"
                            :headers="{'x-access-token':token}"
                            accept="image/*"
                            :show-file-list="false"
                            enctype='multipart/form-data'>
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip"></div>
                          </el-upload>
                        </div>
                      </div>
                    </div>
                    <div style="margin-top: 15px">
                      <div class="clearfix">
                        <span class="title">显示封面</span>
                        <div class="content">
                          <el-radio v-model="articles[articlesIndex].show_cover_pic" label="1">是</el-radio>
                          <el-radio v-model="articles[articlesIndex].show_cover_pic" label="0">否</el-radio>
                        </div>
                      </div>
                    </div>
                    <div class="clearfix" style="margin-top: 15px">
                      <div class="clearfix">
                        <span class="title">打开评论</span>
                        <div class="content">
                          <el-radio v-model="articles[articlesIndex].need_open_comment" label="1">是</el-radio>
                          <el-radio v-model="articles[articlesIndex].need_open_comment" label="0">否</el-radio>
                        </div>
                      </div>
                    </div>
                    <div style="margin-top: 15px">
                      <div class="clearfix">
                        <span class="title">粉丝才可评论</span>
                        <div class="content">
                          <el-radio v-model="articles[articlesIndex].only_fans_can_comment" label="1">是</el-radio>
                          <el-radio v-model="articles[articlesIndex].only_fans_can_comment" label="0">否</el-radio>
                        </div>
                      </div>
                    </div>
                    <div class="clearfix" style="margin-top: 15px">
                      <span class="newsPage">图文内容</span>
                      <div class="ue">
                        <UE :defaultMsg=articles[articlesIndex].content :config=config ref="ue"></UE>
                      </div>
                    </div>
                    <div style="margin-top: 15px">
                      <el-input placeholder="原文地址" v-model="articles[articlesIndex].content_source_url">
                        <template slot="prepend">原文地址</template>
                      </el-input>
                      <p class="tip">
                        图文消息的原文地址，即点击“阅读原文”后的URL，如 https://www.baidu.com
                      </p>
                    </div>
                  </div>
                  <div v-else>
                    <div>
                      <el-input placeholder="标题" v-model="externalNews[externalNewsIndex].title">
                        <template slot="prepend">标题</template>
                      </el-input>
                      <p class="tip">
                        标题不能超过64字符，1中文=2字符，1英文=1字符
                      </p>
                    </div>
                    <div style="margin-top: 15px" v-if="externalNews.length == 1">
                      <el-input placeholder="摘要" v-model="externalNews[externalNewsIndex].description">
                        <template slot="prepend">摘要</template>
                      </el-input>
                      <p class="tip">
                        图文消息的摘要，仅有单图文消息才有摘要，多图文此处为空
                      </p>
                    </div>
                    <div style="margin-top: 15px">
                      <div class="clearfix">
                        <span class="title">图片上传</span>
                        <div class="content">
                          <el-upload
                            class="upload-demo"
                            action="/weChat/uploadImg"
                            :on-success="uploadSuccess"
                            :headers="{'x-access-token':token}"
                            accept="image/*"
                            :show-file-list="false"
                            enctype='multipart/form-data'>
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip"></div>
                          </el-upload>
                        </div>
                      </div>
                    </div>
                    <div style="margin-top: 15px">
                      <el-input placeholder="外部链接" v-model="externalNews[externalNewsIndex].url">
                        <template slot="prepend">外部链接</template>
                      </el-input>
                      <p class="tip">
                        点击图文后跳转的地址，如 https://www.baidu.com
                      </p>
                    </div>
                  </div>
                  <div style="text-align: center;margin-top: 15px">
                    <p class="tip">
                      请图文设置完成后再提交
                    </p>
                    <el-button type="primary" @click="newsClick()">提交</el-button>
                  </div>
                </el-card>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-col>
  </el-row>
</template>
<script>
  import UE from '../../common/UE/UE.vue'
  //  import WXimg from '../../common/js/WXimg'

  export default {
    components: {UE},
    data() {
      return {
        token: '',
        defaultMsg: '', // ueditor配置
        config: {  // ueditor配置
          initialFrameWidth: null,
          initialFrameHeight: 350
        },
        contentHide: false, // 图文类型  false 图文跳转   true 外部链接跳转
        newsReplyBoolean: false, // 避免重复提交
        activeName: 'first',
        newsData: {
          'title': '',
          'menuKey': '',
          'textKey': '',
          'type': 'news',
          'news': {},
          'weight': ''
        },
        articlesIndex: 0,
        articles: [{
          'title': '', // 标题
          'thumb_media_id': '', // 图文消息的封面图片素材id
          'author': '', // 作者
          'digest': '', // 图文消息的摘要，仅有单图文消息才有摘要，多图文此处为空
          'show_cover_pic': '1', // 是否显示封面，0为false，即不显示，1为true，即显示
          'content': '', // 图文消息的具体内容，支持HTML标签，必须少于2万字符，小于1M，且此处会去除JS
          'content_source_url': '', // 图文消息的原文地址，即点击“阅读原文”后的URL
          'need_open_comment': '1', // 是否打开评论，0不打开，1打开
          'only_fans_can_comment': '1', // 是否粉丝才可评论，0所有人可评论，1粉丝才可评论
          'thumb_url': '/static/img/1.jpg' // 图片地址 非微信图文参数
        }],
        externalNewsIndex: 0,
        externalNews: [{
          'title': 'Happy Day',
          'description': 'Is Really A Happy Day',
          'url': 'http://1798xt1229.iask.in/upload/img/966865927113150464.jpg',
          'picurl': 'http://1798xt1229.iask.in/upload/img/966865927113150464.jpg'
        }],
        newsDataList: []
      }
    },
    mounted() {
      this.replyList()
      this.token = this.$store.state.modules.user.token
    },
    methods: {
      // 图片上传方法
      // 上传到服务器
      uploadSuccess(response, file, fileLis) {
        this.externalNews[this.externalNewsIndex].picurl = response.result
      },
      // 上传到微信服务器
      uploadSuccessWX(response, file, fileLis) {
        if (response.code !== -1) {
          this.articles[this.articlesIndex].thumb_url = response.result.url
          this.articles[this.articlesIndex].thumb_media_id = response.result.media_id
        } else {
          this.$message.warning(`图片上传微信服务器错误！错误码：${response.result.errcode}`)
        }
      },
      // 设置编辑器内容
      setContent(html) {
        this.$refs.ue.setUEContent(html)
      },
      // 编辑图文
      editNews(index) {
        if (this.contentHide) {
          this.externalNewsIndex = index
        } else {
          this.articles[this.articlesIndex].content = this.$refs.ue.getUEContent()
          this.articlesIndex = index
          this.setContent(this.articles[this.articlesIndex].content)
        }
      },
      // 删除图文
      delNews(index) {
        if (this.contentHide) {
          this.externalNews.splice(index, 1)
          if (index <= this.externalNewsIndex) {
            this.externalNewsIndex -= 1
          }
        } else {
          this.articles.splice(index, 1)
          if (index <= this.articlesIndex) {
            this.articlesIndex -= 1
          }
        }
        this.setContent(this.articles[this.articlesIndex].content)
      },
      // 新增图文
      addNews() {
        if (this.contentHide) {
          this.externalNews.push({
            'title': 'Happy Day',
            'description': 'Is Really A Happy Day',
            'url': 'http://1798xt1229.iask.in/upload/img/966865927113150464.jpg',
            'picurl': 'http://1798xt1229.iask.in/upload/img/966865927113150464.jpg'
          })
          this.externalNewsIndex = this.externalNews.length - 1
        } else {
          this.articles.push({
            'title': '', // 标题
            'thumb_media_id': '', // 图文消息的封面图片素材id
            'author': '', // 作者
            'digest': '', // 图文消息的摘要，仅有单图文消息才有摘要，多图文此处为空
            'show_cover_pic': '1', // 是否显示封面，0为false，即不显示，1为true，即显示
            'content': '', // 图文消息的具体内容，支持HTML标签，必须少于2万字符，小于1M，且此处会去除JS
            'content_source_url': '', // 图文消息的原文地址，即点击“阅读原文”后的URL
            'need_open_comment': '1', // 是否打0开评论，0不打开，1打开
            'only_fans_can_comment': '1', // 是否粉丝才可评论，0所有人可评论，1粉丝才可评论
            'thumb_url': '/static/img/1.jpg' // 图片地址 非微信图文参数
          })
          this.editNews(this.articles.length - 1)
        }
      },
      // 图文提交
      newsClick() {
        let _self = this
        if (_self.newsReplyBoolean) {
          return
        }
        this.editNews(this.articles.length - 1)
        _self.newsReplyBoolean = true
        if (_self.newsData['title'].length <= 0) {
          _self.$message(`回复名称不能为空`)
          _self.newsReplyBoolean = false
          return
        }
        if (this.contentHide) {
          for (let i = 0; i < _self.externalNews.length; i++) {
            if (_self.externalNews[i].title.length <= 0 || _self.externalNews[i].picurl.length <= 0 || _self.externalNews[i].url.length <= 0) {
              _self.editNews(i)
              _self.$message(`第${i + 1}条图文中有必填项为空`)
              _self.newsReplyBoolean = false
              return
            }
          }
          _self.newsData.news = _self.externalNews
        } else {
          for (let i = 0; i < _self.articles.length; i++) {
            if (_self.articles[i].content.length <= 0 || _self.articles[i].thumb_media_id.length <= 0 || _self.articles[i].title.length <= 0) {
              _self.editNews(i)
              _self.$message(`第${i + 1}条图文中有必填项为空`)
              _self.newsReplyBoolean = false
              return
            }
          }
          _self.newsData.news = _self.articles
        }
        _self.$ajax.post('/weChat/addNews', {
          newsData: _self.newsData,
          newsType: !_self.contentHide
        }).then(function (response) {
          if (response.data.code === 0) {
            _self.replyList()
          } else {
            _self.$message(response.data.msg)
          }
          _self.newsReplyBoolean = false
        }).catch(function (error) {
          _self.newsReplyBoolean = false
          console.log(error)
        })
      },
      // 删除图文回复
      deleteText(id) {
        let _self = this
        _self.$ajax.post('/weChat/deleteReply', {_id: id}).then(function (response) {
          if (response.data.code === 0) {
            _self.replyList()
          } else {
            _self.$message('删除失败！')
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      // 查看详细图文
      viewText(data) {
        let _self = this
        _self.newsData = data
        _self.$ajax.post('/weChat/getMaterial', {id: data.newsData.id}).then(function (response) {
          if (response.data.code === 0) {
            console.info(response.data.data.content)
            if (response.data.data.content.media_id === null) {
              _self.externalNews = response.data.data.content.news
              _self.externalNewsIndex = 0
              _self.contentHide = true
            } else {
              _self.articles = response.data.data.content.news
              _self.articlesIndex = 0
              _self.contentHide = false
              _self.setContent(_self.articles[0].content)
            }
            _self.activeName = 'second'
          } else {
            _self.$message('查看失败！')
          }
          _self.newsReplyBoolean = false
        }).catch(function (error) {
          _self.newsReplyBoolean = false
          console.log(error)
        })
      },
      // 回复列表
      replyList() {
        let _self = this
        _self.$ajax.get('/weChat/replyList?type=news').then(function (response) {
          if (response.data.code === 0) {
            _self.newsDataList = response.data.textDataList
            _self.activeName = 'first'
          } else {
            _self.$message('获取列表失败！')
          }
          _self.newsReplyBoolean = false
        }).catch(function (error) {
          _self.newsReplyBoolean = false
          console.log(error)
        })
      }
    },
    watch: {
      activeName() {
        if (this.activeName === 'first') {
          this.newsData = {
            'title': '',
            'menuKey': '',
            'textKey': '',
            'type': 'news',
            'textVal': '',
            'weight': ''
          }
          this.articles = [{
            'title': '', // 标题
            'thumb_media_id': '', // 图文消息的封面图片素材id
            'author': '', // 作者
            'digest': '', // 图文消息的摘要，仅有单图文消息才有摘要，多图文此处为空
            'show_cover_pic': '1', // 是否显示封面，0为false，即不显示，1为true，即显示
            'content': '', // 图文消息的具体内容，支持HTML标签，必须少于2万字符，小于1M，且此处会去除JS
            'content_source_url': '', // 图文消息的原文地址，即点击“阅读原文”后的URL
            'need_open_comment': '1', // 是否打开评论，0不打开，1打开
            'only_fans_can_comment': '1', // 是否粉丝才可评论，0所有人可评论，1粉丝才可评论
            'thumb_url': '/static/img/1.jpg' // 图片地址 非微信图文参数
          }]
          this.contentHide = false
          this.setContent(this.articles[0].content)
        }
      }
    }
  }
</script>
<style lang="less" scoped="">
  @import './news.less';
</style>
